package com.xyz.frame.api.controller.xiangqin.guest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xyz.frame.api.controller.xiangqin.CommonStatus;
import com.xyz.frame.api.controller.xiangqin.Constant;
import com.xyz.frame.api.controller.xiangqin.MediaType;
import com.xyz.frame.api.controller.xiangqin.StringUtil;
import com.xyz.frame.api.controller.xiangqin.guest.request.GuestOperatorRequest;
import com.xyz.frame.api.controller.xiangqin.guest.response.GuestResponse;
import com.xyz.frame.api.controller.xiangqin.guest.service.AppGuestService;
import com.xyz.frame.api.controller.xiangqin.moment.response.MomentMediaResponse;
import com.xyz.frame.api.controller.xiangqin.moment.service.AppMomentService;
import com.xyz.frame.api.controller.xiangqin.user.response.UserMediaResponse;
import com.xyz.frame.api.controller.xiangqin.user.service.AppUserMediaService;
import com.xyz.frame.bean.enums.RecommendOperatorStatus;
import com.xyz.frame.bean.model.GuestRecommendEntity;
import com.xyz.frame.bean.model.MomentEntity;
import com.xyz.frame.bean.model.User;
import com.xyz.frame.service.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service("appGuestService")
public class AppGuestServiceImpl implements AppGuestService {

    private final GuestRecommendService guestRecommendService;

    private final AppUserMediaService appUserMediaService;

    private final UserService userService;

    private final MomentService momentService;

    private final AppMomentService appMomentService;

    private final DictItemService dictItemService;

    @Autowired
    private UserXqService userXqService;


    public AppGuestServiceImpl(GuestRecommendService guestRecommendService, AppUserMediaService appUserMediaService, UserService userService, MomentService momentService, AppMomentService appMomentService, DictItemService dictItemService) {
        this.guestRecommendService = guestRecommendService;
        this.appUserMediaService = appUserMediaService;
        this.userService = userService;
        this.momentService = momentService;
        this.appMomentService = appMomentService;
        this.dictItemService = dictItemService;
    }

    @Override
    @Transactional
    public GuestResponse newRecommend() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String userId = request.getHeader("userId");
//        LambdaQueryWrapper<GuestRecommendEntity> wrapper =new LambdaQueryWrapper<>();
//        wrapper.eq(GuestRecommendEntity::getUid, userId);
//        wrapper.eq(GuestRecommendEntity::getStatus, RecommendOperatorStatus.DEFAULT.getValue());
//        wrapper.last(" ORDER BY RAND() LIMIT 1 ");
//        GuestRecommendEntity guestRecommendEntity = guestRecommendService.getOne(wrapper);
//        if(guestRecommendEntity != null){
//            User recommendGuest = userService.getUserByUserId(guestRecommendEntity.getGuestUid());
//            GuestResponse guestResponse = buildGuestResponse(recommendGuest);
//            return guestResponse;
//        }

        User userByUid = userXqService.getUserByUid(userId);

        LambdaQueryWrapper<User> oneWrapper = new LambdaQueryWrapper<>();
        oneWrapper.ne(User::getGender,userByUid.getGender());
        oneWrapper.ne(User::getUid,userId);
        oneWrapper.last(" ORDER BY RAND() LIMIT 1 ");
        User recommendGuest = userXqService.getOne(oneWrapper);
        if(Objects.isNull(recommendGuest)){
            return null;
        }
        GuestResponse guestResponse = buildGuestResponse(recommendGuest);
        return guestResponse;

        //新增一个推荐嘉宾
        //添加过滤条件：已经推荐过的嘉宾
//        List<Integer> exitsGuestUidList = guestRecommendService.getExistGuestUidList(userId);

        //添加过滤条件：默认配对反向性别
//        Map<String, Object> params = new HashMap<>();
//        if(user.getGender() == Constant.MAN){
//            params.put("gender", Constant.WOMAN);
//        }else{
//            params.put("gender", Constant.MAN);
//        }
//        params.put("uidList", exitsGuestUidList);
//
//        User recommendGuest = guestRecommendService.getRecommendGuest(params);
//
//        if(recommendGuest == null){
//            throw new XyzShopBindException("找不到合适的嘉宾");
//        }
//
//        GuestRecommendEntity recommend = new GuestRecommendEntity();
//        recommend.setUid(userId);
//        recommend.setGuestUid(recommendGuest.getUid());
//        recommend.setStatus(RecommendOperatorStatus.DEFAULT.getValue());
//        recommend.setCreateTime(new Date());
//        guestRecommendService.save(recommend);
//        GuestResponse guestResponse = buildGuestResponse(recommendGuest);
//        return guestResponse;

    }

    @Override
    public GuestResponse getGuestDetail(User user, String guestUid) {
        User guestUser = userService.getUserByUserId(guestUid);
        GuestResponse guestResponse = buildGuestResponse(guestUser);
        return guestResponse;
    }

    @Override
    public List<GuestResponse> getHistoryRecommend(User user) {
        List<User> userList = guestRecommendService.getHistoryRecommend(user.getUid());
        List<GuestResponse> responseList = new ArrayList<>();
        userList.forEach(User -> {
            GuestResponse response =  buildGuestResponse(User);
            responseList.add(response);
        });
        return responseList;
    }

    @Override
    public void recommendOperator(User user, GuestOperatorRequest request) {
        GuestRecommendEntity guestRecommendEntity = new GuestRecommendEntity();
        guestRecommendEntity.setStatus(RecommendOperatorStatus.DONE.getValue());
        guestRecommendEntity.setUpdateTime(new Date());
        LambdaQueryWrapper<GuestRecommendEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GuestRecommendEntity::getUid, user.getUid());
        wrapper.eq(GuestRecommendEntity::getGuestUid, request.getUid());
        guestRecommendService.update(guestRecommendEntity, wrapper);
    }

    /**
     * 构建嘉宾返回对象
     * @param guestUser 嘉宾用户
     * @return 嘉宾信息返回对象
     */
    private GuestResponse buildGuestResponse(User guestUser){

        //用户基本信息
        GuestResponse response = transformerResponse(guestUser);

        //个人形象图片
        List<UserMediaResponse> userMediaList = appUserMediaService.getUserMediaList(guestUser.getUid(), MediaType.IMAGE.getValue());
        response.setUserMediaList(userMediaList);

        //个人动态数量
        LambdaQueryWrapper<MomentEntity> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(MomentEntity::getUid, guestUser.getUid());
        lambdaQueryWrapper.eq(MomentEntity::getStatus, CommonStatus.CHECKED.getValue());
        response.setMomentListLength(momentService.count(lambdaQueryWrapper));

        //个人动态照片，最多展示四张
        List<MomentMediaResponse> momentMediaList = appMomentService.getMomentImageList(guestUser.getUid());
        response.setMomentMediaList(momentMediaList);

        return response;
    }

    /**
     * 转化对象
     * @param User 用户
     * @return 用户响应
     */
    private GuestResponse transformerResponse(User User){
        GuestResponse response = new GuestResponse();
        BeanUtils.copyProperties(User, response);
        if (!StringUtil.isEmpty(User.getGender())) {
            response.setGender(User.getGender());
            response.setGenderText(dictItemService.getItemName(Constant.DICT_GENDER, User.getGender()));
        }
        if (!StringUtil.isEmpty(User.getBirthday())) {
            response.setBirthdayYear(User.getBirthday().substring(2,4));
        }
        if (!StringUtil.isEmpty(User.getMarriage())) {
            response.setMarriageText(dictItemService.getItemName(Constant.DICT_MARRIAGE, User.getMarriage()));
        }
        if (!StringUtil.isEmpty(User.getEducation())) {
            response.setEducationText(dictItemService.getItemName(Constant.DICT_EDUCATION, User.getEducation()));
        }
        if (!StringUtil.isEmpty(User.getJob())) {
            response.setJobText(dictItemService.getItemName(Constant.DICT_JOB, User.getJob()));
        }
        if (!StringUtil.isEmpty(User.getSalary())) {
            response.setSalaryText(dictItemService.getItemName(Constant.DICT_SALARY, User.getSalary()));
        }
        response.setConstellation("处女座");
        return response;
    }

}